package com.better.common.jwtauth.secruity;

import com.better.common.exception.DescribeException;
import com.better.common.exception.ExceptionEnum;
import com.better.common.utils.Encodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * 后续如果需要使用验证码验证，可以开启此（前期不用）
 * Created by Administrator on 2017/11/14.
 */
@Service
public class JwtAuthenticationProvider implements AuthenticationProvider {
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationProvider.class);
    @Autowired
    private JwtUserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(authentication.getName());
        try {
            //判断用户输入的密码和服务器上已经保存的密码是否一致
            if (MyPasswordEncode.validatePassword(Encodes.decodeBase64String(authentication.getCredentials().toString()),userDetails.getPassword())) {
                logger.info("author success");
                //如果验证通过，将返回一个UsernamePasswordAuthenticaionToken对象
                return new UsernamePasswordAuthenticationToken(userDetails,
                        authentication.getCredentials(), userDetails.getAuthorities());
            }else {
                //如果验证不通过将抛出异常或者返回null
                throw  new DescribeException(ExceptionEnum.PASSWORD_ERROR);
            }
        } catch (Exception e) {
            logger.error("author failed, the error message is: " + e);
            throw e;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}
